package com.winit.schedule.job.tracker;

import javax.annotation.Resource;

import com.winit.schedule.job.tracker.sms.SmsSender;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.winit.schedule.core.conf.Configuration;
import com.winit.schedule.job.tracker.repository.ConsoleDataManager;
import com.winit.schedule.job.tracker.repository.ScheduleDataManager;

public class JobTrackerFactoryBean implements InitializingBean, ApplicationContextAware, DisposableBean, FactoryBean<JobTracker> {

    private JobTracker          jobTracker;

    @Resource
    private ScheduleDataManager scheduleDataManager;

    @Resource
    private ConsoleDataManager  consoleDataManager;

    @Resource
    private SmsSender smsSender;

    private ApplicationContext  applicationContext;

    private Configuration       conf;

    @Override
    public JobTracker getObject() throws Exception {
        return jobTracker;
    }

    @Override
    public Class<?> getObjectType() {
        return JobTracker.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void destroy() throws Exception {
        jobTracker.stop();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public Configuration getConf() {
        return conf;
    }

    public void setConf(Configuration conf) {
        this.conf = conf;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        jobTracker = new JobTracker();
        jobTracker.setScheduleDataManager(scheduleDataManager);
        jobTracker.setConsoleDataManager(consoleDataManager);
        jobTracker.setSmsSender(smsSender);
        jobTracker.init(conf);
        jobTracker.start();
    }
}
